package com.atguigu.config;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Admin;
import com.atguigu.entity.Permission;
import com.atguigu.service.AdminService;

import com.atguigu.service.PermissionService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class MyUserDetailService implements UserDetailsService {
    @Reference
    private AdminService adminService;
    @Reference
    private PermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminService.getByUsername(username);
        //如果admin为null，说明username都不对，直接返回异常
        if(admin==null){
            throw new UsernameNotFoundException("用户名错误");
        }
        //如果admin不为null，说明username正确，需要比较密码。不需要开发者来比较，只要传递数据即可，由SpringSecurity来完成密码的比较
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        //authorities.add(new SimpleGrantedAuthority("role_add"));
        List<String> codeList = permissionService.findCodeListByAdminId(admin.getId());
        for(String code:codeList){
            authorities.add(new SimpleGrantedAuthority(code));
        }
        User user = new User(username,admin.getPassword(),authorities);
        //只需要返回user即可，SpringSecurity进行密码比较，如果密码也正确，登录成功授予authorities权限
        return user;
    }
}
